<template>
  <div>
    <router-view v-if="isAuthPage" />
    <div v-else class="app-container">
      <el-container>
        <el-aside width="200px">
          <el-menu 
            router 
            :default-active="$route.path"
            class="el-menu-vertical"
            background-color="#304156"
            text-color="#bfcbd9"
            active-text-color="#409EFF">
            
            <!-- 在线用户统计 -->
            <div class="online-users-count">
              <el-icon><User /></el-icon>
              <span>在线用户: </span>
              <span class="count">{{ onlineUsers }}</span>
            </div>

            <el-menu-item index="/home">
              <el-icon><HomeFilled /></el-icon>
              <span>首页</span>
            </el-menu-item>
            
            <el-menu-item index="/online-users">
              <el-icon><User /></el-icon>
              <span>用户画像</span>
            </el-menu-item>
            
            <el-sub-menu index="1">
              <template #title>
                <el-icon><Document /></el-icon>
                <span>基金研究</span>
              </template>
              <el-menu-item index="/fund-research">基金列表</el-menu-item>
              <el-menu-item index="/fund-research/tags">标签管理</el-menu-item>
            </el-sub-menu>
            
            <el-sub-menu index="2">
              <template #title>
                <el-icon><Menu /></el-icon>
                <span>因子管理</span>
              </template>
              <el-menu-item index="/factor-management">因子列表</el-menu-item>
              <el-menu-item index="/factor-management/create">创建因子</el-menu-item>
            </el-sub-menu>
            
            <el-sub-menu index="3">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>策略管理</span>
              </template>
              <el-menu-item index="/strategy-management">策略列表</el-menu-item>
              <el-menu-item index="/strategy-management/create">创建策略</el-menu-item>
            </el-sub-menu>
            
            <el-sub-menu index="4">
              <template #title>
                <el-icon><Goods /></el-icon>
                <span>组合产品管理</span>
              </template>
              <el-menu-item index="/portfolio-management">组合列表</el-menu-item>
              <el-menu-item index="/portfolio-management/create">创建组合</el-menu-item>
            </el-sub-menu>
            
            <el-sub-menu index="5">
              <template #title>
                <el-icon><TrendCharts /></el-icon>
                <span>交易管理</span>
              </template>
              <el-menu-item index="/trade-management">交易记录</el-menu-item>
              <el-menu-item index="/trade-management/create">创建交易</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        
        <el-container>
          <el-header height="60px">
            <div class="header-container">
              <h1>智能投顾系统</h1>
              <div class="user-info">
                <el-dropdown>
                  <span class="el-dropdown-link">
                    {{ currentUser?.username || '管理员' }} <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleProfile">个人信息</el-dropdown-item>
                      <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-header>
          
          <el-main>
            <router-view />
          </el-main>
          
          <el-footer height="40px">
            <div class="footer">
              © 2025 智能投顾系统 版权所有
            </div>
          </el-footer>
        </el-container>
      </el-container>
    </div>
  </div>
</template>

<script setup>
import { 
  Document, 
  Menu, 
  Setting, 
  Goods, 
  TrendCharts,
  ArrowDown,
  HomeFilled,
  User
} from '@element-plus/icons-vue'
import { computed, onMounted, onBeforeUnmount } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()

const currentUser = computed(() => store.state.user.user)
const onlineUsers = computed(() => {
  console.log('Computing onlineUsers, current state:', store.state.user.onlineUsers)
  return store.state.user.onlineUsers
})

const isAuthPage = computed(() => {
  return ['/login', '/register'].includes(router.currentRoute.value.path)
})

// 定期更新在线用户数
const updateOnlineUsers = async () => {
  try {
    const count = await store.dispatch('user/getOnlineUsers')
    console.log('Updated online users count:', count)
  } catch (error) {
    console.error('Failed to update online users:', error)
  }
}

// 处理个人信息
const handleProfile = () => {
  router.push('/profile')
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await store.dispatch('user/logout')
    router.push('/login')
  } catch (error) {
    console.error('退出失败:', error)
    ElMessage.error('退出失败，请重试')
  }
}

// 处理页面关闭或刷新
const handleBeforeUnload = (event) => {
  const user = store.state.user.user
  if (user && user.id) {
    // 使用 sendBeacon 发送登出请求
    const logoutUrl = `${import.meta.env.VITE_API_BASE_URL}/api/auth/logout/${user.id}`
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${localStorage.getItem('token')}`
    }
    const blob = new Blob([JSON.stringify({ deviceInfo: navigator.userAgent })], { type: 'application/json' })
    navigator.sendBeacon(logoutUrl, blob)
  }
}

onMounted(() => {
  console.log('Component mounted, initializing online users count')
  // 初始获取在线用户数
  updateOnlineUsers()
  // 每30秒更新一次在线用户数
  const timer = setInterval(updateOnlineUsers, 30000)
  
  // 添加页面关闭事件监听
  window.addEventListener('beforeunload', handleBeforeUnload)
})

onBeforeUnmount(() => {
  // 移除事件监听
  window.removeEventListener('beforeunload', handleBeforeUnload)
  clearInterval(timer)
})
</script>

<style>
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

#app {
  font-family: 'Microsoft YaHei', sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  height: 100%;
}

.app-container {
  height: 100vh;
}

.el-container {
  height: 100%;
}

.el-aside {
  background-color: #304156;
  color: #bfcbd9;
}

.el-menu-vertical {
  height: 100%;
}

.el-header {
  background-color: #fff;
  color: #333;
  border-bottom: 1px solid #e6e6e6;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.user-info {
  cursor: pointer;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
}

.el-footer {
  background-color: #f5f7fa;
  color: #606266;
  text-align: center;
  line-height: 40px;
}

/* 在线用户统计样式 */
.online-users-count {
  padding: 20px;
  color: #bfcbd9;
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.online-users-count .count {
  color: #67c23a;
  font-weight: bold;
}
</style> 